import { drizzle } from 'drizzle-orm/postgres-js'
import postgres from 'postgres'
import { chatsTable, messagesTable } from './schema';
import { and, desc, eq } from 'drizzle-orm';

const client = postgres(process.env.DATABASE_URL!)
const db = drizzle({ client });
export { db }
// chats
export const createChat = async (title: string, userId: string, model: string) => {
  try {
    const [newChat] = await db.insert(chatsTable).values({
      title,
      userId,
      model
    }).returning()
    return newChat
  } catch (error) {
    console.log("error creating chat", error)
    return null
  }
}

export const getChat = async (chatId: number, userId: string) => {//该用户的某个聊天
  try {
    const chat = await db.select().from(chatsTable).where(and(eq(chatsTable.id, chatId), eq(chatsTable.userId, userId)))
    if (chat.length === 0) {
      return null
    }
    return chat[0]
  } catch (error) {
    console.log("error getting chat", error)
    return null
  }
}

export const getChats = async (userId: string) => {//该用户的聊天列表
  try {
    const chats = await db.select().from(chatsTable).where(eq(chatsTable.userId, userId)).orderBy(desc(chatsTable.id))

    return chats
  } catch (error) {
    console.log("error getting chats", error)
    return null
  }
}

// messages
export const createMessage = async (chat_id: number, content: string, role: string) => {//根据聊天id插入聊天
  try {
    const [newMessage] = await db.insert(messagesTable).values({
      content: content,
      chatId: chat_id,
      role: role
    }).returning()
    return newMessage
  } catch (error) {
    console.log("error createMessage", error)
    return null
  }
}

export const getMessagesByChatId = async (chatId: number) => {//根据聊天id获取聊天
  try {
    const messages = await db.select().from(messagesTable).where(eq(messagesTable.chatId, chatId))
    return messages
  } catch (error) {
    console.log("error getMessagesByChatId", error)
    return null
  }
}

export const deleteChat = async (chatId: number, userId: string) => {
  try {
    // 先删除关联的消息
    await db.delete(messagesTable)
      .where(eq(messagesTable.chatId, chatId));
    
    // 再删除聊天记录
    const [deletedChat] = await db.delete(chatsTable)
      .where(and(
        eq(chatsTable.id, chatId),
        eq(chatsTable.userId, userId)
      ))
      .returning();
    
    return deletedChat;
  } catch (error) {
    console.log("error deleting chat", error);
    return null;
  }
}